package com.qinggeng.project.system.service.impl;

import com.qinggeng.common.enums.*;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.DateUtils;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.framework.config.mq.MQSendUtils;
import com.qinggeng.framework.config.mq.dto.MessageOrdersMessageDTO;
import com.qinggeng.framework.config.mq.enums.MQTypeEnum;
import com.qinggeng.project.system.domain.*;
import com.qinggeng.project.system.mapper.OrdersReturnMapper;
import com.qinggeng.project.system.service.*;
import com.qinggeng.project.tool.pay.service.AliPayService;
import com.qinggeng.project.tool.pay.service.WxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author 吴鹏飞
 * @date 2020/8/31
 */
@Service
public class OrdersReturnServiceImpl implements IOrdersReturnService {
    @Resource
    private OrdersReturnMapper ordersReturnMapper;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IOrdersGoodsService ordersGoodsService;

    @Autowired
    private IUserConsumeService userConsumeService;

    @Autowired
    private IUserMessageService userMessageService;

    @Autowired
    private IDistributionPointService pointService;

    @Autowired
    private IUserWalletService userWalletService;
    @Autowired
    private MQSendUtils mqSendUtils;



    /**
     * 根据Id查询订单信息
     *
     * @param ordersReturnId
     * @return
     */
    @Override
    public OrdersReturn selectOrdersReturnById(Long ordersReturnId) {
        return ordersReturnMapper.selectOrdersReturnById(ordersReturnId);
    }

    /**
     * 查询订单信息列表
     *
     * @param ordersReturn
     * @return
     */
    @Override
    public List<OrdersReturn> selectOrdersReturnList(OrdersReturn ordersReturn) {
        return ordersReturnMapper.selectOrdersReturnList(ordersReturn);
    }

    /**
     * 插入订单信息
     *
     * @param ordersReturn
     * @return
     */
    @Override
    @Transactional
    public int insertOrdersReturn(OrdersReturn ordersReturn,Long userId) {
        OrdersReturn oldOrdersReturn = ordersReturnMapper.selectOrdersReturnByOrdersNo(ordersReturn.getOrdersNo());
        //退单已关闭
        if (oldOrdersReturn != null && oldOrdersReturn.getStatus() == 4){
            throw new CustomException("退单已申请过");
        }
        return ordersReturnMapper.insertOrdersReturn(ordersReturn);
    }

    /**
     * 修改订单信息
     *
     * @param ordersReturn
     * @return
     */
    @Override
    public int updateOrdersRetrun(OrdersReturn ordersReturn) {
        return ordersReturnMapper.updateOrdersRetrun(ordersReturn);
    }

    /**
     * 根据Id删除订单信息
     *
     * @param ordersReturnId
     * @return
     */
    @Override
    public int deleteOrdersReturnById(Long ordersReturnId) {
        return deleteOrdersReturnById(ordersReturnId);
    }

    /**
     * 批量删除订单信息
     *
     * @param ordersReturnIds
     * @return
     */
    @Override
    public int deleteOrdersRetrunByIds(Long[] ordersReturnIds) {
        return ordersReturnMapper.deleteOrdersRetrunByIds(ordersReturnIds);
    }

    /**
     * 确认退货
     * @param ordersReturnId
     * @return
     */
    @Override
    @Transactional
    public void confirmReturn(Long ordersReturnId, BigDecimal payment) {
        OrdersReturn ordersReturn = ordersReturnMapper.selectOrdersReturnById(ordersReturnId);
        if (ordersReturn == null) {
            throw new CustomException("退货订单不存在");
        }
        if (ordersReturn.getStatus()== OrdersReturnStatusEnum.已关闭.getValue()){
            throw new CustomException("退货订单已关闭");
        }
        if (ordersReturn.getStatus()== OrdersReturnStatusEnum.已退单.getValue()){
            throw new CustomException("退货订单已退过");
        }
        if (ordersReturn.getStatus()== OrdersReturnStatusEnum.退单失败.getValue()){
            throw new CustomException("退货订单为退货失败订单无法退货");
        }
        if (ordersReturn.getStatus()== OrdersReturnStatusEnum.已取消.getValue()){
            throw new CustomException("退款订单已取消");
        }

        Orders orders = ordersService.selectOrdersById(ordersReturn.getOrdersId());
        if (orders == null){
            throw new CustomException("订单不存在");
        }

        try {
            //支付状态为已状态
            if (orders.getPayStatus().equals(CommonEnum.STATUS_20.getValue())){
                //微信退款
                if (ordersReturn.getPaymentType()==1){
                    wxPayService.refund(orders.getOrdersNo(),payment);
                //支付宝退款
                }else if (ordersReturn.getPaymentType()==2){
                    aliPayService.refund(orders.getOrdersNo(),payment);
                }else {
                    throw new CustomException("退款失败");
                }
            }

        }catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("退款失败");
        }

        //用户收支明细添加退款记录
        userConsumeService.addUserConsume(orders.getUserId(),payment,orders.getOrdersId(),UserConsumeEnum.订单退款,"+");

        //根据订单ID查询配送点信息
        DistributionPoint point=pointService.selectDistributionPointByOrdersId(orders.getOrdersId());
        if(point!=null){
            //根据订单ID查询订单提成
            BigDecimal percentage=ordersGoodsService.getOrdersPercentageByOrdersId(orders.getOrdersId());
            //如果用户收支明细中存在订单提成记录，扣除订单提成
            UserConsume where=new UserConsume();
            where.setUserId(point.getCourierId());
            where.setFkId(orders.getOrdersId());
            where.setConsumeType(UserConsumeEnum.订单提成.getValue());
            List<UserConsume> userConsumeList=userConsumeService.selectUserConsumeList(where);
            if(!CollectionUtils.isEmpty(userConsumeList)){
                userWalletService.subtractWallet(point.getCourierId(),percentage,orders.getOrdersId(),UserConsumeEnum.提成撤回);
            }
        }

        //订单状态改为已退单
        ordersReturn.setStatus(1);
        ordersReturn.setUpdateTime(DateUtils.getNowDate());

        updateOrdersRetrun(ordersReturn);

        //修改订单状态为已退单
        orders.setStatus(CommonEnum.STATUS_60.getValue());
        //修改支付状态为已退款
        orders.setPayStatus(CommonEnum.STATUS_40.getValue());
        orders.setUpdateTime(DateUtils.getNowDate());
        //设置退款金额
        orders.setPayment(payment);
        ordersService.updateOrders(orders);

        //发送消息，保存
        MessageOrdersMessageDTO ordersMessageDTO=new MessageOrdersMessageDTO();
        ordersMessageDTO.setType(MQTypeEnum.ORDERS_MESSAGE_JPUSH.getType());
        ordersMessageDTO.setUserType(UserTypeEnum.MEMBER.getCode());
        ordersMessageDTO.setOrdersNo(orders.getOrdersNo());
        ordersMessageDTO.setMark("订单退款通知");
        ordersMessageDTO.setMessage("尊敬的用户,您的订单"+orders.getOrdersNo()+"已退款!");
        mqSendUtils.sendAsynMessage(ordersMessageDTO);

    }

    /**
     * 根据订单编号查询退单信息
     * @param ordersNo
     * @return
     */
    @Override
    public OrdersReturn selectOrdersReturnByOrdersNo(String ordersNo) {
        return ordersReturnMapper.selectOrdersReturnByOrdersNo(ordersNo);

    }

    @Override
    public boolean checkOrdersReturnService(OrdersReturn ordersReturn) {
         String ordersNo= ordersReturn.getOrdersNo();
         if (StringUtils.isEmpty(ordersNo)){
             throw  new CustomException("订单编号不能空");
         }
        Long ordersId= ordersReturn.getOrdersId();
        if (null ==ordersId){
            throw  new CustomException("ordersI不能空");
        }

        BigDecimal payment= ordersReturn.getPayment();
        if (payment.compareTo(BigDecimal.ZERO)>0){
            throw  new CustomException("金额不能为空");
        }
         OrdersReturn order=selectOrdersReturnByOrdersNo( ordersNo);
         if (null ==order){
             return  ordersReturnMapper.insertOrdersReturn(ordersReturn)>=1;
         }
        return ordersReturnMapper.updateOrdersRetrun(ordersReturn)>=1;
    }
}
